package org.nalai.tools;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;

import java.io.ByteArrayOutputStream;

public class ExecUtil {

    @SuppressWarnings("unused")
    public String ping(String ip) {

        try {

            String command = "ping " + ip;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
            CommandLine commandline = CommandLine.parse(command);
            DefaultExecutor exec = new DefaultExecutor();
            exec.setExitValues(null);

            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
            exec.setStreamHandler(streamHandler);
            exec.execute(commandline);

            String out = outputStream.toString("gbk");
            String error = errorStream.toString("gbk");

            return out + error;

        } catch (Exception e) {

            e.printStackTrace();
            return e.toString();

        }

    }

    /**
     * 执行命令
     *
     * @param cmd 命令
     * @return 执行命令返回的结果
     * @throws Exception
     */
    public String cmd(String cmd) throws Exception {

        CommandLine commandline = CommandLine.parse(cmd);
        DefaultExecutor executor = new DefaultExecutor();

        //创建监控时间60秒，超过60秒则中端执行
        ExecuteWatchdog watchdog = new ExecuteWatchdog(30 * 1000);
        executor.setWatchdog(watchdog);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
        executor.setStreamHandler(streamHandler);
        executor.execute(commandline);

        String out = outputStream.toString("gbk");
        String error = errorStream.toString("gbk");

        return out + error;
    }
}
